layui.define(['laypage'], function (exports) {
    "use strict";
    let MOD_NAME = 'table_card';
    let $ = layui.jquery;
    let laypage = layui.laypage;
    let AjaxData = [];
    let AjaxUtil = {
        get: function (url, param, fun, buttonElementList, async = true) {
            if (buttonElementList) {
                //按钮置灰
                this.buttonDisabled(buttonElementList);
            }
            let token = localStorage.getItem('token') || '';
            var ajaxOption = {
                cache: false,
                async: async,
                url: url,
                data: param,
                method: "get",
                dataType: "json",
                headers: {token: token},
                success: function (resultData) {
                    if (buttonElementList) {
                        AjaxUtil.buttonDisabledRemove(buttonElementList);
                    }
                    AjaxUtil.errorHanler(resultData, fun)
                },
                error: function (err) {

                }
            };
            layui.jquery.ajax(ajaxOption);
        },

        post: function (url, param, fun, contentType, formData, buttonElementList, async = true) {
            if (buttonElementList) {
                this.buttonDisabled(buttonElementList);
            }
            let loading = layui.layer.load(0, {
                shade: false
            });
            let token = localStorage.getItem('token') || '';
            let ajaxOption = {
                cache: false,//关闭缓存
                async: async,//默认为true
                url: url,
                method: "post",
                dataType: "json",
                headers: {token: token},
                success: function (resultData) {
                    if (buttonElementList) {
                        AjaxUtil.buttonDisabledRemove(buttonElementList);
                    }
                    AjaxUtil.errorHanler(resultData, fun);
                    layui.layer.close(loading);
                },
                error: function (err) {

                }
            };
            if (param) {
                ajaxOption.data = param;
            }

            layui.jquery.ajax(ajaxOption);
        },
        postJson: function (url, param, fun, buttonElementList, async) {
            this.post(url, param, fun, true, false, buttonElementList, async);
        },
        postForm: function (url, param, fun, buttonElementList, async) {
            this.post(url, param, fun, false, true, buttonElementList, async);
        },
        send: function (method, url, param, fun, contentType, async = true, buttonElementList) {
            if ("get" == method.toLowerCase()) {
                this.get(url, param, fun, buttonElementList, async)
            }
            if ("post" == method.toLowerCase()) {
                if (contentType) {
                    this.postJson(url, param, fun, buttonElementList, async)
                } else {
                    this.postForm(url, param, fun, buttonElementList, async)
                }
            }
        },
        buttonDisabledRemove: function (buttonElementList) {
            if (buttonElementList instanceof Array) {
                layui.jquery.each(buttonElementList, function (index, item) {
                    this.buttonDisabledRemoveOne(item);
                })
            } else {
                this.buttonDisabledRemoveOne(buttonElementList);
            }
        },
        buttonDisabledRemoveOne: function (buttonElement) {
            var DISABLED = 'layui-btn-disabled';
            if (buttonElement) {
                buttonElement.removeClass(DISABLED);
                buttonElement.removeAttr('disabled');
            }

        },

        buttonDisabled: function (buttonElementList) {
            //防止重复点击: 单击之后提交按钮不可选,防止重复提交
            if (buttonElementList instanceof Array) {
                layui.jquery.each(buttonElementList, function (index, item) {
                    this.buttonDisabledOne(item);
                })
            } else {
                this.buttonDisabledOne(buttonElementList);
            }

        },
        buttonDisabledOne: function (buttonElement) {
            var DISABLED = 'layui-btn-disabled';
            if (buttonElement) {
                buttonElement.addClass(DISABLED); // 添加样式
                buttonElement.attr('disabled', 'disabled');  // 添加属性
            }
        },
        errorHanler: function (res, fun) {
            if (res.code == 201) {
                layer.confirm('系统监测到您还没有登录', function (index) {
                    window.open("/admin/index/login/", '_top')
                })
                return;
            }

            if (res.code != 200) {
                if (res.msg) {
                    layer.msg(res.msg, {icon: 2})
                } else {
                    layer.msg("接口异常", {icon: 2})
                }
                return;
            }
            fun(res)
        }
    }


    let RuiNuoPage = {
        set: function (options) {
            let that = this;
            that.config = $.extend({}, that.config, options);
            return that;
        },
        index: layui.table_card ? (layui.table_card.index + 10000) : 0,
        that: [],
        BindButton: function (that, i = 0) {

            let rows = AjaxData[i];
            let elem = InitData['table']['elem'];
            let button = InitData['table']['button'] || [];
            let dropdown = [];
            button.forEach((item, index) => {
                dropdown.push({id: index, title: item.title});
            });
            layui.dropdown.render({
                elem: that,
                show: true,
                data: dropdown,
                click: function (data, othis) {
                    layui.engine_table.ButtonAciton(data.id, 2, elem, rows)
                },
                align: 'right', // 右对齐弹出
                style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' //设置额外样式
            })

        }
    };

    let Class = function (options) {
        let that = this;
        that.index = ++RuiNuoPage.index;
        that.config = $.extend({}, that.config, RuiNuoPage.config, options);
        that.render();
        return that;
    }
    let sortHtml = '<span class="layui-table-sort layui-inline" lay-sort="${lay-sort}"  style="margin-left: 0px">' +
        '<i class="layui-edge layui-table-sort-asc" title="升序"></i>' +
        '<i class="layui-edge layui-table-sort-desc" title="降序"></i>' +
        '</span>';
    //默认配置
    Class.prototype.config = {
        cols: [],//列名
        data: [],//数据
        colMd: 3,//列占行的宽度 3/12
        url: '',
        method: 'post',
        contentType: false,
        where: {},
        sortName: '', //排序字段
        sortType: '',//排序类型 asc desc
        toolbar: '', // 右侧工具条 #id
        eventList: {}// 事件列表
        , page: {
            disable: true,
            limit: 12,
            limits: [10, 30, 50, 100, 200, 300, 500]
        },
        sortList: [],
        multiSortSwitch: false // 是否开启多排序
    };
    //渲染视图
    Class.prototype.render = function () {
        var that = this
            , conf = that.config
            , elem = conf.elem
        ;
        $(elem).css({"position": "relative"})
        that.setData();
        that.renderData()
        that.renderPage()
        return that;
    }


    Class.prototype.reload = function (options) {
        var that = this
            , conf = that.config
            , elem = conf.elem
        that.mergeConf(options)
        $(elem).find(".card_table_con").remove();
        $(elem).find(".RuiNuoPage-page").remove();
        that.setData();
        that.renderData()
        that.renderPage(conf.where.page, conf.where.limit)
        return that;

    }
    /**
     * 加载分页对象
     */
    Class.prototype.renderPage = function (curr, limit) {
        var that = this
            , conf = that.config
            , data = conf.data
            , elem = conf.elem
        if (data && conf.page.disable) {
            $(elem).append("<div class='RuiNuoPage-page'></div>")
            laypage.render({
                elem: $(elem + ' div:last') //注意，这里的 test1 是 ID，不用加 # 号
                , count: data.total //数据总数，从服务端得到
                , limit: conf.where.limit
                , limits: conf.page.limits
                , curr: curr || 1
                , layout: ['prev', 'page', 'next', 'limit', 'count', 'refresh', 'skip']
                , jump: function (obj, first) {
                    if (!first) {
                        that.reload({where: {page: obj.curr, limit: obj.limit}})
                    }
                }
            });
        }

    }

    /**
     * 数据转换视图
     */
    Class.prototype.renderData = function () {
        let that = this
            , conf = that.config
            , data = conf.data
            , elem = conf.elem
            , style = InitData['table']['style'] || 4;
        ;
        if (data && data.records.length != 0) {
            AjaxData = data.records;
            let htmlCon = '<div class="card_table_con"></div>';
            $(elem).html("");
            $(elem).append(htmlCon);
            let tpl_html = '<div><div class="layui-card"><div class="layui-card-body"></div"></div</div">';
            let rowElem = $(elem).find('.card_table_con').eq(0);
            let cols = conf.cols;

            data.records.forEach((item, index) => {
                let TPL = $(tpl_html).get(0);
                if (index % (12 / conf.colMd) == 0) {
                    $(rowElem).append("<div class='layui-row layui-col-space15 row-hight'></div>")
                }
                let headdd = 2;
                let SelectHtml = '';
                cols.forEach((val, i) => {
                    let search = val.search || '';
                    if (search == 'select') {
                        SelectHtml += '<li>' + val.title + '</li>';
                    }
                    let add = 1;
                    if (val.field && headdd == 2) {
                        headdd = 1;
                        let value = item[val.field];
                        let head = '<div class="title">' + value + '</div>';
                        let head_class = '';
                        if (style == 5) {
                            let mime = layui.public.getMine(value);
                            switch (mime) {
                                case "png":
                                case "jpg":
                                case "jpeg":
                                case "gif":
                                case "ico":
                                    head = '<div class="file" style="background: url(' + value + ');background-size: cover;background-position: center;"></div>';
                                    break;
                                default:
                                    head = '<div class="file">' + mime + '</div>';
                            }
                            head_class = 'file_con';
                        }
                        $(TPL).find('.layui-card').prepend('<div class="layui-card-header ' + head_class + '">' + head + '</div>');
                        add = 2;
                    }
                    if (val.title == "操作") {
                        add = 2;
                        $(TPL).find('.layui-card-header').append('<div class="card_more ruinuo-icon icon-elipsis" onclick="layui.table_card.BindButton(this,' + index + ')"></div>');
                    }
                    if (add == 1) {
                        if (val.field) {
                            $(TPL).find('.layui-card-body').append('<ul><li>' + val.title + '</li><li>' + item[val.field] + '</li></ul>');
                        }

                    }
                })
                let html = '<div class="layui-col-md' + conf.colMd + '">' + $(TPL).html() + '</div>';
                $(rowElem).find(".layui-row.row-hight:last").append(html);
                let aViewList = $(rowElem).find(".ruinuo_view:last");
                if (aViewList.length) {
                    $(aViewList).each(function (rr) {
                        $(aViewList[rr]).dblclick(function () {
                            var objv = {};
                            objv.data = item;
                            RuiNuoView(objv);
                        })
                    })
                }
            })
            that.sortBindClick()
        } else {
            $(".card_table_con").html('<div class="ruinuo_nodata">无数据</div>')
        }
        layui.form.render();
    }

    /**
     * 加载事件
     * @param id
     * @param call
     * @returns {*}
     */
    Class.prototype.on = function (id, call) {
        var that = this
            , conf = that.config
        conf.eventList[id] = call;
    }
    /**
     * 加载数据
     */
    Class.prototype.setData = function () {
        var that = this
            , conf = that.config
        //获取数据
        if (conf.sortName && conf.sortType) {
            conf.where.sortName = conf.sortName
            conf.where.sortType = conf.sortType
        } else {
            conf.where.sortName = ''
            conf.where.sortType = ''
        }
        if (!conf.where.page) {
            conf.where.page = 1;
        }
        if (!conf.where.limit) {
            conf.where.limit = conf.page.limit
        }
        if (conf.multiSortSwitch) {
            conf.where.sortList = conf.sortList
        }

        AjaxUtil.send(conf.method, conf.url, conf.where, function (res) {

            if (typeof conf.parseData === 'function') {
                conf.data = conf.parseData(res)
            } else {
                conf.data = res.data;
            }
        }, conf.contentType, false, '')
    }

    /**
     * 合并配置信息
     * @param options
     */
    Class.prototype.mergeConf = function (options) {
        var that = this
            , conf = that.config

        if (options) {
            for (var key in options) {
                if (conf[key]) {
                    conf[key] = Object.assign(conf[key], options[key])
                } else {
                    conf[key] = Object.assign({}, options[key])
                }
            }
        }


    }


    /**
     * 绑定排序
     */
    Class.prototype.sortBindClick = function () {
        var that = this
            , conf = that.config
        $('.layui-table-sort-asc').click(function () {
            let sortName = that.findFiled($(this).parent().prev().text());
            let sortType = "asc";
            conf.sortName = sortName;
            conf.sortType = sortType;
            if (conf.multiSortSwitch) {
                let sortObj = conf.sortList.find(item => item.sortName == sortName);
                if (sortObj) {
                    conf.sortList.remove(sortObj)
                }
                conf.sortList.push({sortName: sortName, sortType: sortType})
            }


            that.reload()
        })
        $('.layui-table-sort-desc').click(function () {
            that.findFiled($(this).parent().prev().text())
            let sortName = that.findFiled($(this).parent().prev().text())
            let sortType = "desc";
            conf.sortName = sortName;
            conf.sortType = sortType;
            if (conf.multiSortSwitch) {
                let sortObj = conf.sortList.find(item => item.sortName == sortName);
                if (sortObj) {
                    conf.sortList.remove(sortObj)
                }
                conf.sortList.push({sortName: sortName, sortType: sortType})
            }

            that.reload()
        })
        $('.card-single-title').click(function () {
            conf.sortName = ''
            conf.sortType = ''
            if (conf.multiSortSwitch) {
                let sortName = that.findFiled($(this).text())
                let removeSort = conf.sortList.find(item => item.sortName == sortName);
                if (removeSort) {
                    conf.sortList.remove(removeSort)
                }
            }
            that.reload()
        })
    }


    /**
     * 查找标题对应字段名
     * @param title
     * @returns {*}
     */
    Class.prototype.findFiled = function (title) {
        var that = this
            , conf = that.config
        let cols = conf.cols;
        return cols.find(item => item.title == title).field;
    }

    /**
     * 获取sortHtml内容
     * @returns {string|string}
     */
    Class.prototype.sortHtml = function (colObj) {
        var that = this
            , conf = that.config
        if (conf.multiSortSwitch) {
            let sortObj = conf.sortList.find(item => item.sortName == colObj.field);
            return (sortObj) ? sortHtml.replace("${lay-sort}", sortObj.sortType) : sortHtml;
        }
        return (conf.sortName && conf.sortType && conf.sortName == colObj.field) ? sortHtml.replace("${lay-sort}", conf.sortType) : sortHtml;
    }
    //核心入口
    RuiNuoPage.render = function (options) {
        var ins = new Class(options);
        if (options.id) {
            RuiNuoPage.that[options.id] = ins;
        }
        return ins;
    };
    //操作当前实例
    RuiNuoPage.reload = function (id, options) {
        if (!RuiNuoPage.that[id]) {
            console.log("table id = " + id + "，未初始化或者table没有配置id")
            return;
        }
        RuiNuoPage.that[id].reload(options)
    }
    exports(MOD_NAME, RuiNuoPage);
});
